package cn.broadmax.boot.shiro;

import cn.broadmax.boot.base.message.SResult;
import cn.broadmax.boot.util.JsonUtils;
import jexx.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author jeff
 * @date 2020/6/20
 */
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    public static final String ACCESS_TOKEN_HEADER = "Access-Token";

    public static final String AUTHORIZATION_HEADER_START = "Bearer ";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            log.info("url={}", ((HttpServletRequest)request).getRequestURI());
            return executeLogin(request, response);
        } catch (Exception e) {
            sendUnAuthException(e.getMessage(), (HttpServletResponse)response);
        }
        return false;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        String token = getToken(request);
        if(StringUtil.isEmpty(token)){
            return false;
        }

        JwtToken jwtToken = new JwtToken(token);
        getSubject(request, response).login(jwtToken);
        return true;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication required: sending 401 Authentication challenge response.");
        }
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        String authcHeader = getAuthcScheme() + " realm=\"" + getApplicationName() + "\"";
        httpResponse.setHeader(AUTHENTICATE_HEADER, authcHeader);
        sendUnAuthException("未授权", httpResponse);
        return false;
    }

    private String getToken(ServletRequest request){
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String header = httpRequest.getHeader(ACCESS_TOKEN_HEADER);
        if(StringUtil.isNotEmpty(header)){
            return header;
        }
        header = httpRequest.getHeader(AUTHORIZATION_HEADER);
        if(StringUtil.isNotEmpty(header)){
            if(header.startsWith(AUTHORIZATION_HEADER_START)){
                return header.substring(AUTHORIZATION_HEADER_START.length());
            }
        }
        return null;
    }

    private void sendUnAuthException(String message, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        try(PrintWriter writer = response.getWriter()){
            writer.print(JsonUtils.toJSONString(SResult.unauth(message)));
        }
        catch (IOException e){
            log.error("", e);
        }
    }

}
